var express = require('express');
var path = require('path');
var domain= require('domain');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// 设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 中间件调用
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static(__dirname + '/public'));
//app.use(express.static(__dirname + '/files'));
//app.use(express.static(__dirname + '/uploads'));
//uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));


// 所有请求异常处理
app.use(function (req,res, next) {
    var serverDomain = domain.create();
    //监听domain的错误事件
    serverDomain.on('error', function (err) {
        // todo:日志记录，返回错误的信息要详细
        res.statusCode = 666;
        res.json({sucess:false, message: '服务器异常',err:err.message});
        serverDomain.dispose();
    });
    serverDomain.add(req);
    serverDomain.add(res);
    serverDomain.run(next);
});

// 初始化路由配置，一定要在404前面初始化
require('./config/routes')(app);

// 路由404错误处理
app.use(function(req, res, next) {
    //var err = new Error('Not Found');
    //err.status = 404;
    //next(err);
    res.statusCode = 404;
    res.json({sucess:false, message: '请求路径不存在',err:''});
});

// 初始化数据库连接
global.dbHelper = require( './db/dbServer');












// development error handler
// will print stacktrace
//if (app.get('env') === 'development') {
//  app.use(function(err, req, res, next) {
//    res.status(err.status || 500);
//    res.render('error', {
//      message: err.message,
//      error: err
//    });
//  });
//}
//
//// production error handler
//// no stacktraces leaked to user
//app.use(function(err, req, res, next) {
//  res.status(err.status || 500);
//  res.render('error', {
//    message: err.message,
//    error: {}
//  });
//});


module.exports = app;
